package com.hmily.cloud.asm.core;

/**
 * <h1>16进制转换工具类。</h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2024/6/1 19:45
 */
public class HexUtils {

    /**
     * <h2>将十六进制字符串转字节数组。</h2>
     *
     * @param hexString 十六进制字符串
     * @return 字节数组
     */
    public static byte[] convertHexStringToBytes(String hexString) {
        // 判空
        if (hexString == null || hexString.length() == 0) {
            return null;
        }

        // 合法性校验
        if (!hexString.matches("[a-fA-F0-9]*") || hexString.length() % 2 != 0) {
            return null;
        }

        // 计算
        int mid = hexString.length() / 2;
        byte[] bytes = new byte[mid];
        for (int i = 0; i < mid; i++) {
            bytes[i] = Integer.valueOf(hexString.substring(i * 2, i * 2 + 2), 16).byteValue();
        }

        return bytes;
    }
}